package com.fh.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fh.order.entity.Order;
import com.fh.order.entity.OrderItem;
import com.fh.order.entity.OrderOperateHistory;
import com.fh.order.mapper.OrderMapper;
import com.fh.order.service.OrderItemService;
import com.fh.order.service.OrderOperateHistoryService;
import com.fh.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author zs
 * @since 2021-10-21
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Autowired
    private OrderItemService orderItemService;
    @Resource
    private OrderMapper orderMapper;
    @Autowired
    private OrderOperateHistoryService orderOperateHistoryService;

    @Override
    public void rollBackStock(String orderSn) {
        //查询当前订单数据
        QueryWrapper<Order> wrapper=new QueryWrapper<>();
        wrapper.eq("order_sn",orderSn);
        wrapper.eq("status",0);
        Order order = super.getOne(wrapper);
        if(order!=null)
        {
            order.setStatus(5);
            super.updateById(order);
            QueryWrapper<OrderItem> wrapper1=new QueryWrapper<>();
            wrapper1.eq("order_sn",orderSn);
            List<OrderItem> orderItemList = orderItemService.list(wrapper1);
            orderItemList.forEach(orderItem -> {
                String productSkuCode = orderItem.getProductSkuCode();
                Integer payCount = orderItem.getProductQuantity();
                orderMapper.updateStock(productSkuCode,payCount);

            });
            //记录订单操作
            OrderOperateHistory orderOperateHistory=new OrderOperateHistory();
            orderOperateHistory.setOrderId(order.getId());
            orderOperateHistory.setCreateTime(new Date());
            orderOperateHistory.setOrderStatus(0);
            orderOperateHistory.setOperateMan("系统");
            orderOperateHistoryService.save(orderOperateHistory);
        }


    }
}
